package com.hifar.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hifar.abi.flow.bean.prd.NodeUserBean;
import com.hifar.abi.flow.bean.pri.PriCreateBean;
import com.hifar.abi.flow.utils.FlowApiUtils;
import com.hifar.abi.flow.utils.FlowConst;
import com.hifar.fw.core.busi.annotation.BusiMethod;
import com.hifar.fw.core.busi.annotation.Business;
import com.hifar.fw.core.busi.annotation.Transactional;
import com.hifar.fw.dao.bean.QueryBean;
import com.hifar.fw.dao.runner.SqlRunner;
import com.hifar.fw.dao.utils.DaoUtils;
import com.hifar.fw.json.JsonUtils;
import com.hifar.fw.utils.bean.BusiConst;
import com.hifar.fw.utils.bean.BusiRequest;
import com.hifar.fw.utils.bean.BusiResponse;
import com.hifar.fw.utils.consts.SysConsts;
import com.hifar.fw.utils.exception.BusinessException;
import com.hifar.fw.utils.id.IdUtils;
import com.hifar.fw.utils.lang.CollectionUtils;
import com.hifar.fw.utils.lang.DateUtils;
import com.hifar.fw.utils.lang.NumberUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.fw.utils.page.PageBean;
import com.hifar.fw.utils.sql.SqlUtils;

@Business(name = "HfDemoProjectTestBusiness")
public class HfDemoProjectTestBusiness {


	public SqlRunner getSqlRunner() {

		SqlRunner sqlRunner = DaoUtils.getSqlRunnerManger().getSqlRunner(SysConsts.DS_CODE_DEFAULT);
		return sqlRunner;
	}

	public SqlRunner getSqlRunner(BusiRequest request) {
		SqlRunner sqlRunner = DaoUtils.getSqlRunnerManger().getSqlRunner(SysConsts.DS_CODE_DEFAULT);
		return sqlRunner;
	}

	@BusiMethod
	public BusiResponse add(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		String userName = request.getIdName();
		String userId = request.getUserIdStr();
		long tm = DateUtils.getTimeLong();
		double d=1100/0;
		// 业务参数
		String testName = StringUtils.trimNull(request.getData("testName"));
		String testLocation = StringUtils.trimNull(request.getData("testLocation"));
		String testBatchNo = StringUtils.trimNull(request.getData("testBatchNo"));
		String testStage = StringUtils.trimNull(request.getData("testStage"));
		String testInstitute = StringUtils.trimNull(request.getData("testInstitute"));
		long testStartTime = NumberUtils.parseLong(request.getData("testStartTime"));
		long testStopTime = NumberUtils.parseLong(request.getData("testStopTime"));
		String typeId = StringUtils.trimNull(request.getData("typeId"));
		String procCode = StringUtils.trimNull(request.getData("procCode"));
		String flowId = StringUtils.trimNull(request.getData("flowId"));
		String remarks = StringUtils.trimNull(request.getData("remarks"));
		int rowSort = NumberUtils.parseInt(request.getData("rowSort"), 1000);
		String id = IdUtils.uuid32();
		Map<String, Object> insertMap = new HashMap<>(2);
		insertMap.put("id", id);
		insertMap.put("tenantId", tenantId);
		insertMap.put("testName", testName);
		insertMap.put("testLocation", testLocation);
		insertMap.put("testBatchNo", testBatchNo);
		insertMap.put("testStage", testStage);
		insertMap.put("testInstitute", testInstitute);
		insertMap.put("testStartTime", testStartTime);
		insertMap.put("testStopTime", testStopTime);
		insertMap.put("typeId", typeId);
		insertMap.put("procCode", procCode);
		insertMap.put("flowId", flowId);

		insertMap.put("rowSort", rowSort);
		insertMap.put("remarks", remarks);
		insertMap.put("createUserId", userId);
		insertMap.put("createUserName", userName);
		insertMap.put("createTime", tm);
		insertMap.put("updateUserId", userId);
		insertMap.put("updateUserName", userName);
		insertMap.put("updateTime", tm);
		getSqlRunner(request).insert(request, "hf_demo_project", insertMap);
		Map<String, Object> rsMap = new HashMap<>(2);
		rsMap.put("id", id);
		response.setData(rsMap);
		return response;
	}

	@BusiMethod
	public BusiResponse modifyById(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		String userId = request.getUserIdStr();
		String userName = request.getIdName();
		long tm = DateUtils.getTimeLong();
		// 业务参数
		String id = StringUtils.trimNull(request.removeData("id"));
		String testName = StringUtils.trimNull(request.getData("testName"));
		String testLocation = StringUtils.trimNull(request.getData("testLocation"));
		String testBatchNo = StringUtils.trimNull(request.getData("testBatchNo"));
		String testStage = StringUtils.trimNull(request.getData("testStage"));
		String testInstitute = StringUtils.trimNull(request.getData("testInstitute"));
		long testStartTime = NumberUtils.parseLong(request.getData("testStartTime"));
		long testStopTime = NumberUtils.parseLong(request.getData("testStopTime"));
		String typeId = StringUtils.trimNull(request.getData("typeId"));
		String procCode = StringUtils.trimNull(request.getData("procCode"));
		String flowId = StringUtils.trimNull(request.getData("flowId"));
		String remarks = StringUtils.trimNull(request.getData("remarks"));
		int rowSort = NumberUtils.parseInt(request.getData("rowSort"), 1000);
		// 验证参数
		// 准备数据
		Map<String, Object> updateMap = new HashMap<>(20);
		updateMap.put("testName", testName);
		updateMap.put("testLocation", testLocation);
		updateMap.put("testBatchNo", testBatchNo);
		updateMap.put("testStage", testStage);
		updateMap.put("testInstitute", testInstitute);
		updateMap.put("testStartTime", testStartTime);
		updateMap.put("testStopTime", testStopTime);
		updateMap.put("typeId", typeId);
		updateMap.put("procCode", procCode);
		updateMap.put("flowId", flowId);
		updateMap.put("rowSort", rowSort);
		updateMap.put("remarks", remarks);
		updateMap.put("updateUserId", userId);
		updateMap.put("updateUserName", userName);
		updateMap.put("updateTime", tm);
		String whereSql = " tenant_id = ?  and id = ?";
		int num = this.getSqlRunner(request).update(request, "hf_demo_project", updateMap, whereSql, tenantId, id);
		Map<String, Object> rsMap = new HashMap<>(2);
		rsMap.put("num", num);
		response.setData(rsMap);
		return response;
	}

	@BusiMethod
	public BusiResponse logicRemoveById(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		String userId = request.getUserIdStr();
		String userName = request.getIdName();
		long tm = DateUtils.getTimeLong();
		// 业务参数
		String id = StringUtils.trimNull(request.getData("id"));
		List<String> ids = CollectionUtils.valueOfList(id);
		// 验证参数
		if (ids == null || ids.size() < 1) {
			response.setCodeAndMsg(BusiConst.CODE_PARAM, "请先选择需要删除的数据！");
			return response;
		}
		String sql = "update hf_demo_project set status=?,update_user_id=?,update_time=?,update_user_name=? where tenant_id = ? and ";
		sql += SqlUtils.createInPrepared("id", ids.size(), false);
		List<Object> params = new ArrayList<>();
		params.add(SysConsts.LOGIC_DELETE);
		params.add(userId);
		params.add(tm);
		params.add(userName);
		params.add(tenantId);
		params.addAll(ids);
		int num = this.getSqlRunner(request).execBySql(request, sql, params.toArray());
		Map<String, Object> dataMap = new HashMap<>(2);
		dataMap.put("num", num);
		response.setData(dataMap);
		return response;
	}

	@BusiMethod
	public BusiResponse queryById(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		// 业务参数
		String id = StringUtils.trimNull(request.getData("id"));
		String sql = "select * from hf_demo_project where tenant_id = ? and id= ? and status != ? ";
		Map<String, Object> map = this.getSqlRunner(request).queryBySql(request, sql, tenantId, id,
				SysConsts.LOGIC_DELETE);
		if (map != null) {
			response.setData(map);
		} else {
			response.setData(new HashMap<String, Object>(0));
		}
		return response;
	}

	@BusiMethod
	public BusiResponse listPage(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		// 业务参数
		QueryBean queryBean = new QueryBean(request);
		queryBean.append("select * from hf_demo_project where 1=1 ");
		queryBean.addColumns("hf_demo_project", SysConsts.DS_CODE_DEFAULT);
		queryBean.addConditionEquals("tenantId", tenantId);
		queryBean.addConditionNotEquals("status", SysConsts.LOGIC_DELETE);
		queryBean.setOrderStr("createTime desc");
		queryBean.compileRequest(request);
		PageBean<List<Map<String, Object>>> page = getSqlRunner(request).listPage(request, queryBean);
		convertResult(request, page.getRows());
		response.setData(page);
		return response;
	}

	@BusiMethod
	public BusiResponse listAll(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		// 业务参数
		QueryBean queryBean = new QueryBean(request);
		queryBean.append(" select * from hf_demo_project where 1=1 ");
		queryBean.addColumns("hf_demo_project", SysConsts.DS_CODE_DEFAULT);
		queryBean.addConditionEquals("tenantId", tenantId);
		queryBean.addConditionNotEquals("status", SysConsts.LOGIC_DELETE);
		queryBean.setOrderStr("createTime desc");
		queryBean.compileRequest(request);
		List<Map<String, Object>> list = getSqlRunner(request).list(request, queryBean);
		convertResult(request, list);
		response.setData(list);
		return response;
	}

	protected void convertResult(BusiRequest request, List<Map<String, Object>> dataList) {
		if (dataList != null && dataList.size() > 0) {
			for (Map<String, Object> map : dataList) {
				convertResult(request, map);
			}
		}
	}

	protected void convertResult(BusiRequest request, Map<String, Object> dataMap) {
		if (dataMap != null && dataMap.size() > 0) {

		}
	}
	
	@SuppressWarnings("unchecked")
	@BusiMethod
	@Transactional(name = SysConsts.DS_CODE_DEFAULT)
	public BusiResponse publish(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		// 接收参数
		String id = StringUtils.trimNull(request.getData("id"));
		if (StringUtils.isEmpty(id)) {
			response.setCodeAndMsg(BusiConst.CODE_PARAM, "实验id不能为空！");
			return response;
		}
		String sql = "select * from hf_demo_project where tenant_id=? and id=? and status!=?";
		Map<String, Object> projectMap = this.getSqlRunner().queryBySql(request, sql, tenantId, id,
				SysConsts.LOGIC_DELETE);
		if (projectMap == null || projectMap.size() < 1) {
			response.setCodeAndMsg(BusiConst.CODE_PARAM, "实验不存在！");
			return response;
		}
		String testStage= StringUtils.trimNull(projectMap.get("testStage"));

		String testName = StringUtils.trimNull(projectMap.get("testName"));
		String procCode = StringUtils.trimNull(projectMap.get("procCode"));
		String flowId = StringUtils.trimNull(projectMap.get("flowId"));
		if (StringUtils.isEmpty(procCode)) {
			procCode = "develop_tdm_flow";// 这里临时写死一个流程编码
		}
		String procName = "demo项目审批";
		String status = StringUtils.trimNull(projectMap.get("status"));
	   String nextUserId = StringUtils.trimNull(request.getData("nextUserId"));
	   String varValueSr = StringUtils.trimNull(request.getData("varValueSr"));
	   String nextUserName = StringUtils.trimNull(request.getData("nextUserName"));

	   List<NodeUserBean> nextUserList = new ArrayList<>();
	   List<String> nextUserIdList = CollectionUtils.valueOfList(nextUserId);
	   String name="";
		if (nextUserIdList.size() > 0) {
			 sql = "select id,id_name from base_org_user where status = ? and " + SqlUtils.createInPrepared("id", nextUserIdList.size(), false);
			List<Object> params = new ArrayList<Object>();
			params.add(SysConsts.STATUS_ENABLE);
			params.addAll(nextUserIdList);
			List<Map<String, Object>> userMapList = getSqlRunner(request).listBySql(request, sql, params.toArray());
			for (Map<String, Object> map : userMapList) {
				nextUserId = StringUtils.trimNull(map.get("id"));
				 name = StringUtils.trimNull(map.get("idName"));
				 NodeUserBean nodeUserBean = new NodeUserBean();
				 nodeUserBean.setId(nextUserId);
				 nodeUserBean.setName(name);
				 nextUserList.add(nodeUserBean);
			}
		}
	  
		// 流程审批，调起审批流程
		PriCreateBean createBean = new PriCreateBean();
		createBean.setBusiId(id);
		createBean.setProTitle(procName);
		createBean.setProCode(procCode);
		createBean.setPriAbstract("实验名称[" + testName + "]");
		 createBean.setNextUserList(nextUserList);
		//如果开始节点是分支流程，必须添加分支变量的处理代码
		varValueSr = StringUtils.trimNull(request.getData("varValueSr"));
	    Map<String,Object> value=new HashMap<String,Object>();
	    if(JsonUtils.isJson(varValueSr)) {
	       value=JsonUtils.toMap(varValueSr);
	    }else {
		   value=new HashMap<String,Object>();
	    }
	    if(testStage.equals("物理")) {
		   value.put("testStage", "物理");
	    }else {
		   value.put("testStage", "化学");
	    }
	    createBean.getVarMap().putAll(value);
	    
	    
		if (StringUtils.isNotEmpty(flowId)) {
			createBean.setPriId(flowId);
		}
		BusiResponse proResponse = FlowApiUtils.createAndStartProcessInstance(request, createBean);
		if (proResponse.getCode() == BusiConst.CODE_SUCCESS) {
			if (StringUtils.isEmpty(flowId)) {// 首次提交
				String newFlowId = null;
				try {
					Map<String, Object> resMap = (Map<String, Object>) proResponse.getData();
					if (resMap != null) {
						newFlowId = StringUtils.trimNull(resMap.get("id"));
					}
				} catch (Exception e) {
					newFlowId = null;
				}
				if (StringUtils.isEmpty(newFlowId)) {
					throw new BusinessException("调起演示项目审批流程(" + procCode + ")流程后没有返回流程id！");
				}
				sql = "update hf_demo_project set proc_code=?, status=?,flow_id=? where id=? and status in(?,?)";
				int num = this.getSqlRunner().execBySql(request, sql, procCode, 3, newFlowId, id, 1, 5);
				if (num < 1) {
					//throw new BusinessException("数据发布失败，请刷新后重试！");
					response.setCodeAndMsg(BusiConst.CODE_PARAM, "数据发布失败，请刷新后重试！");
				}
			} else {// 再次提交，在回调里处理

			}
		} else {
			//throw new BusinessException(proResponse.getMsg());
			response.setCodeAndMsg(BusiConst.CODE_PARAM, proResponse.getMsg());
		}
		return response;
	}

	

	/**
	 * @Description 发布获取创建节点的下一个节点
	 */
	@SuppressWarnings("unchecked")
	@BusiMethod
	@Transactional(name = SysConsts.DS_CODE_DEFAULT)
	public BusiResponse getCreateNextNode(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数
		String tenantId = request.getTenantIdStr();
		// 接收参数
		String id = StringUtils.trimNull(request.getData("id"));
		if (StringUtils.isEmpty(id)) {
			response.setCodeAndMsg(BusiConst.CODE_PARAM, "实验id不能为空！");
			return response;
		}
		String sql = "select * from hf_demo_project where tenant_id=? and id=? and status!=?";
		Map<String, Object> projectMap = this.getSqlRunner().queryBySql(request, sql, tenantId, id,
				SysConsts.LOGIC_DELETE);
		if (projectMap == null || projectMap.size() < 1) {
			response.setCodeAndMsg(BusiConst.CODE_PARAM, "实验不存在！");
			return response;
		}
		String testStage= StringUtils.trimNull(projectMap.get("testStage"));

		String testName = StringUtils.trimNull(projectMap.get("testName"));
		String procCode = StringUtils.trimNull(projectMap.get("procCode"));
		String flowId = StringUtils.trimNull(projectMap.get("flowId"));
		if (StringUtils.isEmpty(procCode)) {
			procCode = "develop_tdm_flow";// 这里写死一个流程编码
		}
		String procName = "demo项目审批";
		String status = StringUtils.trimNull(projectMap.get("status"));
	   List<NodeUserBean> nextUserList = new ArrayList<>();
	   //如果开始节点是分支流程，必须添加分支变量的处理代码
	   String varValueSr = StringUtils.trimNull(request.getData("varValueSr"));
	   Map<String,Object> value=new HashMap<String,Object>();
	   if(JsonUtils.isJson(varValueSr)) {
	     value=JsonUtils.toMap(varValueSr);
	   }else {
		   value=new HashMap<String,Object>();
	   }
	   if(testStage.equals("物理")) {
		   value.put("testStage", "物理");
	   }else {
		   value.put("testStage", "化学");
	   }
		// 流程审批，调起审批流程
		PriCreateBean createBean = new PriCreateBean();
		createBean.setBusiId(id);
		createBean.setProTitle(procName);
		createBean.setProCode(procCode);
		createBean.setPriAbstract("实验名称[" + testName + "]");
		createBean.setNextUserList(nextUserList);
	    createBean.getVarMap().putAll(value);
		if (StringUtils.isNotEmpty(flowId)) {
			createBean.setPriId(flowId);
		}
		BusiResponse proResponse = FlowApiUtils.getNextNodeCreate(request, createBean);
		
		return proResponse;
	}

	/**
	 * @Description 流程审批回调
	 */
	@BusiMethod
	public BusiResponse publishCallBack(BusiRequest request) {
		//status 1未提交 3流程已发起 4审批已通过 5驳回申请
		BusiResponse response = new BusiResponse();
		// 接收参数
		String callbackType = StringUtils.trimNull(request.getData("callbackType"));
		String nodeType = StringUtils.trimNull(request.getData("nodeType"));
		String busiId = StringUtils.trimNull(request.getData("busiId"));
		if (StringUtils.isEmpty(busiId)) {
			throw new BusinessException("实验数据id为空！");
		}
		// 获取发布数据
		String sql = "select * from hf_demo_project where id=? and status!=?";// 状态：1 待提交 3已提交 4审核通过 5 审核驳回 99删除
		Map<String, Object> dataMap = this.getSqlRunner().queryBySql(request, sql, busiId, SysConsts.LOGIC_DELETE);
		String flowId=StringUtils.trimNull(dataMap.get("flowId"));
		String testStage=StringUtils.trimNull(dataMap.get("testStage"));
		if (dataMap == null || dataMap.size() < 1) {
			throw new BusinessException("实验数据不存在！");
		}
		if (FlowConst.CALLBACK_PROCESS_END.equals(callbackType)) {// 最终审批通过
			sql = "update hf_demo_project set status=? where id=? ";
			int num = this.getSqlRunner().execBySql(request, sql, 4, busiId);
			//if (num < 1) {
			//	throw new com.hifar.fw.utils.exception.BusinessException("系统繁忙，请稍后重试！");
			//}
		} else if (FlowConst.CALLBACK_PROCESS_REFUSE.equals(callbackType)) {// 最终审批驳回
			sql = "update hf_demo_project set status=? where id=? ";
			int num = this.getSqlRunner().execBySql(request, sql, 5, busiId);
			//if (num < 1) {
			//	throw new com.hifar.fw.utils.exception.BusinessException("系统繁忙，请稍后重试！");
			//}
		} else if (FlowConst.CALLBACK_TASK_COMMIT_BEFORE.equals(callbackType)
				&& FlowConst.NODE_TYPE_START.equals(nodeType)) {// 开始节点再次提交(通过任务)
			
			sql = "update flow_pri_var set value=? where pri_id=? and code=?";
			int num = this.getSqlRunner().execBySql(request, sql, testStage, flowId, "testStage");
		}
		return response;
	}

	// 对于回退的任务可以进行撤销
	@BusiMethod
	@Transactional(name = SysConsts.DS_CODE_DEFAULT)
	public BusiResponse killPriOfTask(BusiRequest request) {
		BusiResponse response = new BusiResponse();
		// 系统参数

		String userId = request.getUserIdStr();
		String flowId = StringUtils.trimNull(request.getData("flowId"));
		if ("".equals(flowId)) {
			response.setCodeAndMsg(BusiConst.CODE_PARAM, "流程id不能为空！");
			return response;
		}
		String sql = "SELECT * FROM flow_pri_task t WHERE t.pri_id=?  " + "AND t.status=2 AND t.user_id=?  "
				+ " ORDER BY create_time desc  ";
		List<Object> params = new ArrayList<Object>();
		params.add(flowId);
		params.add(userId);
		List<Map<String, Object>> taskList = this.getSqlRunner().listBySql(request, sql, params.toArray());
		String taskId = "";

		if (taskList != null && !taskList.isEmpty()) {
			taskId = StringUtils.trimNull(taskList.get(0).get("id"));
		} else {
			response.setCodeAndMsg(BusiConst.CODE_PARAM, "任务不存在，无法撤销！");
			return response;
		}
		BusiRequest requestArg = new BusiRequest();
		requestArg.getData().put("taskId", taskId);
		response = FlowApiUtils.killPriOfTask(requestArg);
		if (response.getCode() == BusiConst.CODE_SUCCESS) {
			// 修改demo项目项目的状态为待提交
			String updateSql = "update hf_demo_project set status=? ,flow_id=null,proc_code=null  where flow_id=?  ";
			this.getSqlRunner().execBySql(request, updateSql, 1, flowId);

		}

		return response;
	}



}
